<template>
    <div class="components_edit_modal">
        <el-dialog title="添加课程考核方案" :visible.sync="state" :show-close="true" :close-on-click-modal="false">
            <el-form :model="form" :rules="rules" ref="form">
                <el-form-item label="学校：" >
                    {{form.schoolName}}
                </el-form-item>
                <el-form-item label="学院：" >
                    {{form.secondSchoolName}}
                </el-form-item>
                <el-form-item label="所属专业：" >
                    {{form.professionName}}
                </el-form-item>
                <el-form-item label="所授课程：" >
                    {{form.courseName}}
                </el-form-item>

                <el-form-item label="录入方式：">
                    <el-radio-group v-model="entryMode" @change="changeRadio">
                        <el-radio label="hand">手动</el-radio>
                        <el-radio label="copy">复制</el-radio>
                    </el-radio-group>
                </el-form-item>
                <br>


                <div v-show="handShow">
                    <el-form-item label="考核内容：" prop="content" class="lineblock textareaBox">
                        <el-input
                            type="textarea"
                            :maxlength="1000"
                            :autosize="{ minRows: 2, maxRows: 4}"
                            placeholder="请输入考核内容"
                            v-model="form.content">
                        </el-input>
                    </el-form-item>
                    <br>
                    <el-form-item label="考核要求：" prop="requirement" class="lineblock textareaBox">
                        <el-input
                            type="textarea"
                            :maxlength="1000"
                            :autosize="{ minRows: 2, maxRows: 4}"
                            placeholder="请输入考核要求"
                            v-model="form.requirement">
                        </el-input>
                    </el-form-item>
                    <br>
                    <el-form-item label="备注：" class="lineblock textareaBox">
                        <el-input
                            type="textarea"
                            :maxlength="500"
                            :autosize="{ minRows: 2, maxRows: 4}"
                            placeholder="请输入备注"
                            v-model="form.remark">
                        </el-input>
                    </el-form-item>
                    <br>
                    <el-form-item label="成绩配比：" class="lineblock scrollBarX">
                        <el-table :data="scoreTypeList" style="width: 100%" show-summary :summary-method="getSummaries" class="components_edit_tables bordright">
                            <el-table-column prop="name" label="考核项" align="center" header-align="center"></el-table-column>

                            <el-table-column label="占比(%)" align="center" header-align="center">
                                <template slot-scope="scope">
                                    <el-input-number v-model="form.detailList[scope.$index].scorePercent" :min="0" :max="100" size="mini">
                                    </el-input-number>
                                </template>
                            </el-table-column>

                            <el-table-column  label="备注说明" align="center" header-align="center">
                                <template slot-scope="scope">
                                    <el-input v-model="form.detailList[scope.$index].remark" :maxlength="500">
                                    </el-input>
                                </template>
                            </el-table-column>
                        </el-table>
                        <!--
                        <table>
                            <thead>
                                <tr>
                                    <th>考核项</th>
                                    <th>占比(%)</th>
                                    <th>备注说明</th>
                                </tr>
                            </thead>

                            <tbody>
                                <tr v-for="(item, index) in scoreTypeList">
                                    <td>
                                        {{item.name}}
                                    </td>
                                    <td>
                                       <el-input-number v-model="scorePercent" :min="0" :max="100">
                                         </el-input-number>
                                    </td>
                                    <td>
                                        <el-input v-model="remark" :maxlength="500">
                                        </el-input>
                                    </td>
                                </tr>
                                <tr>
                                    <td>合计</td>
                                    <td>{{scorePercentTotal}}</td>
                                    <td></td>
                                </tr>
                            </tbody>
                        </table>
                        -->
                    </el-form-item>
                </div>

                <div v-show="copyShow">
                    <el-form-item label="考核方案列表：" class="lineblock scrollBarX">
                       <el-table ref="multipleTable" :data="courseAssessmentList" style="width: 100%" class="components_edit_tables bordright">
                            <el-table-column prop="semesterText" label="选择" width="50px" align="center">
                                <template slot-scope="scope">
                                    <el-checkbox v-model="courseAssessmentList[scope.$index].check" @change="checkScheme(scope.row.id,scope.$index)"></el-checkbox>
                                </template>
                            </el-table-column>

                            <el-table-column :show-overflow-tooltip="true" prop="semester" label="学期" align="center">
                            </el-table-column>

                            <el-table-column :show-overflow-tooltip="true" prop="schoolName" label="学校" align="center">
                            </el-table-column>

                            <el-table-column :show-overflow-tooltip="true" prop="professionName" label="专业" align="center">
                            </el-table-column>

                            <el-table-column :show-overflow-tooltip="true" prop="grade" label="年级" align="center"
                                :formatter="(row,column,cellValue) => cellValue + '级'">
                            </el-table-column>

                            <el-table-column :show-overflow-tooltip="true" prop="courseName" label="课程" align="center">
                            </el-table-column>
                        </el-table>
                    </el-form-item>
                </div>

            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="save" size="small">保 存 草 稿</el-button>
                <el-button type="primary" @click="submit" size="small">提 交</el-button>
                <el-button @click="state = false;" size="small">关 闭</el-button>
            </div>

        </el-dialog>
        
        <!-- 流程相关 -->
        <flow-init ref="courseFlow">
        </flow-init >
    </div>
</template>

<script>
    import {enums} from '@/constant'
    import { mapGetters } from 'vuex'
    export default {
        components: {

        },
        data() {
            return {
                 // state: false,
                 entryMode: "hand",
                 handShow: true,
                 copyShow: false,
                 rules: {
                    grade: [
                        { required: true, message: '请选择年级', trigger: 'change', type: 'string'},
                    ],
                    content: [
                        { required: true, message: '请填写考核内容', trigger: 'blur', type: 'string'},

                    ],
                    requirement: [
                        { required: true, message: '请填写考核要求', trigger: 'blur', type: 'string'},
                    ],
                    attachment: [
                        { required: true, message: '请选择上传附件', trigger: 'change', type: 'array'},
                    ],
                 },
                form: {
                    id: null,
                    trainPlanCourseId: null,
                    schoolId:null,
                    schoolName: null,
                    secondSchoolId:null,
                    secondSchoolName: null,
                    professionId:null,
                    professionName:null,
                    grade:null,
                    courseNo:null,
                    courseName:null,
                    teacherId:null,
                    content:null,
                    requirement:null,
                    remark:null,
                    detailList:[],
                },
                // 成绩类型列表
                scoreTypeList:null,
                // 获取课程考核方案列表
                courseAssessmentList: null,
            }
        },
        created() {
            // 获取课程考核方案列表
            this.getCourseAssessmentList();
            // 获取成绩类型列表
            this.getScoreType();
        },
        mounted() {},
        computed:{
            state: {
                get: function () {
                    if(this.$store.getters.getCourseAssessmentSchemeAdd.state == true){
                        // 处理和组装数据
                        let data = this.$store.getters.getCourseAssessmentSchemeAdd.data;
                        this.form.trainPlanCourseId = data.trainPlanCourseId;
                        this.form.schoolName = data.schoolName;
                        this.form.schoolId = data.schoolId;
                        this.form.secondSchoolName = data.secondSchoolName;
                        this.form.secondSchoolId = data.secondSchoolId;
                        this.form.professionName = data.professionName;
                        this.form.professionId = data.professionId;
                        this.form.grade = data.grade;
                        this.form.courseName = data.courseName;
                        this.form.courseNo = data.courseNo;
                        // this.form.teacherId = data.teacherId;
                        // 重置字段和校验
                        this.$nextTick(function(){
                            this.$refs['form'].resetFields();
                        })
                        this.form.remark = null;
                        // 手填课程考核方案表格数据清空
                        if(this.form.detailList.length > 0 ){
                            this.form.detailList.forEach((item,index)=>{
                                item.scorePercent = 0;
                                item.remark = null;
                            })
                        }
                        // 复制考核方案
                        if( this.courseAssessmentList !=null){
                            this.courseAssessmentList.forEach((item,index)=>{
                                item.check = false;
                            })
                        }
                        // 默认选中：手填
                        this.entryMode = "hand";
                        this.handShow = true;
                        this.copyShow = false;
                    }
                    return this.$store.getters.getCourseAssessmentSchemeAdd.state;
                },
                set: function (v) {
                   if(!v){
                        this.$store.commit("COURSE_ASSESSMENT_SCHEME_ADD", {dialogState: v, data: null});
                   }
                }
            }
        },
        methods: {
            // 打开模态框
            showDialog(id){
                this.teachMaterialsId = id;
                // 获取基本信息
                this.getTeachMaterialsInfo();
                //this.state = true;
                this.$nextTick(function(){
                    this.$refs['form'].resetFields();
                })
            },
             // 获取课程考核方案列表
            getCourseAssessmentList() {
                let vm = this;
                vm.axios.get(api.courseAssessmentScheme.queryAll).then((response) => {
                    if (response.data.success) {
                        vm.courseAssessmentList = JSON.parse(JSON.stringify(response.data.data));
                        // 设置选中的值
                        vm.courseAssessmentList.forEach((item,index)=>{
                            vm.$set(vm.courseAssessmentList[index],"check", false)
                        })
                    } else {
                        vm.$message.error(response.data.msg);
                    }
                })
            },
            // 获取成绩类型列表
            getScoreType(){
                let vm = this;
                vm.axios.get(api.dictsTypesSubListUrl, {
                     params: {
                        type: "assessment_score_type",
                    }
                }).then((response) => {
                    if (response.data.success) {
                        vm.scoreTypeList = JSON.parse(JSON.stringify(response.data.data));
                        vm.scoreTypeList.forEach((item,index)=>{
                            let detailModel = {
                                scoreType : item.value,
                                scorePercent : 0,
                                remark: null,
                            }
                            vm.form.detailList.push(detailModel);
                        })
                    } else {
                        vm.$message.error(response.data.msg);
                    }
                })
            },
            // 保存
            save() {
                let vm = this;
                /* let flowSubject = this.form.schoolName + "-" + this.form.secondSchoolName + "-"
                                    + this.form.professionName + "-" + this.form.grade + "级"; */
                if(vm.entryMode == 'hand'){   //手填
                    vm.$refs['form'].validate((valid) => {
                        if (valid) {
                            // 校验数据
                            let scorePercentTotal = vm.form.detailList.reduce((curr, item)=>{
                                return curr + Number(item.scorePercent);
                            }, 0)
                            if(scorePercentTotal > 100){
                                vm.$message({
                                    type: 'warn',
                                    message: '成绩占比总和不能大于100%',
                                });
                                return;
                            }
                            // 处理数据
                            vm.form.id = null;
                            // console.log(this.form);
                            // return;
                            vm.axios.post(api.courseAssessmentScheme.insert, vm.form)
                            .then((response) => {
                                if (response.data.success) {
                                  /*   vm.$message({
                                        type: 'success',
                                        message: response.data.msg,
                                    }); */
                                    // 关闭弹出窗口
                                    vm.state = false;
                                    // 刷新table
                                    vm.$parent.$refs.courseAssessmentTable.$emit('vuetable:refresh');
                                    //  打开流程定义界面
                                    // vm.$refs.courseFlow.showDialog(flowSubject , `jx_course_assessment_scheme`, response.data.data);
                                } else {
                                    vm.$message.error(response.data.msg);
                                }
                            })
                        } else {
                            return false;
                        }
                    });
                }else if(vm.entryMode == 'copy'){   //拷贝

                    let check = _.find(vm.courseAssessmentList, {check: true});
                    if(check == null){
                        vm.$message({
                            type: 'warn',
                            message: '请先选中课程考核方案！',
                        });
                        return;
                    }
                    vm.form.id = check.id;
                    // console.log(vm.form)
                    // return;
                    vm.axios.post(api.courseAssessmentScheme.copyInsert, vm.form)
                        .then((response) => {
                            if (response.data.success) {
                               /*  vm.$message({
                                    type: 'success',
                                    message: response.data.msg,
                                }); */
                                // 关闭弹出窗口
                                vm.state = false;
                                // 刷新table
                                vm.$parent.$refs.courseAssessmentTable.$emit('vuetable:refresh');
                                //  打开流程定义界面
                                // vm.$refs.courseFlow.showDialog(flowSubject, `jx_course_assessment_scheme`, response.data.data);
                                } else {
                                    vm.$message.error(response.data.msg);
                                }
                    })
                }
            },
            // 提交
            submit() {
                let vm = this;
                let flowSubject = this.form.schoolName + "-" + this.form.secondSchoolName + "-"
                                    + this.form.professionName + "-" + this.form.grade + "级";
                if(vm.entryMode == 'hand'){   //手填
                    vm.$refs['form'].validate((valid) => {
                        if (valid) {
                            // 校验数据
                            let scorePercentTotal = vm.form.detailList.reduce((curr, item)=>{
                                return curr + Number(item.scorePercent);
                            }, 0)
                            if(scorePercentTotal > 100){
                                vm.$message({
                                    type: 'warn',
                                    message: '成绩占比总和不能大于100%',
                                });
                                return;
                            }
                            // 处理数据
                            vm.form.id = null;
                            // console.log(this.form);
                            // return;
                            //  打开流程定义界面
                            //vm.$refs.courseFlow.showDialog(flowSubject , `jx_course_assessment_scheme`, null, vm.form, api.courseAssessmentScheme.insert);
                            let data = {
                                actionType: "save",
                                flowSubject: flowSubject,
                                businessCode: `jx_course_assessment_scheme`,
                                businessId: null,
                                businessForm: vm.form,
                                businessUrl: api.courseAssessmentScheme.insert
                            };
                            vm.$store.commit(`FLOW_INIT`, {"dialogState": true, "data": data});
                        } else {
                            return false;
                        }
                    });
                }else if(vm.entryMode == 'copy'){   //拷贝

                    let check = _.find(vm.courseAssessmentList, {check: true});
                    if(check == null){
                        vm.$message({
                            type: 'warn',
                            message: '请先选中课程考核方案！',
                        });
                        return;
                    }
                    vm.form.id = check.id;
                    // console.log(vm.form)
                    // return;
                    //  打开流程定义界面
                    let data = {
                        actionType: "save",
                        flowSubject: flowSubject,
                        businessCode: `jx_course_assessment_scheme`,
                        businessId: null,
                        businessForm: vm.form,
                        businessUrl: api.courseAssessmentScheme.copyInsert
                    };
                    vm.$store.commit(`FLOW_INIT`, {"dialogState": true, "data": data});
                }
            },
            // 切换radio  手填/复制
            changeRadio(){
                let vm = this;
                if(vm.entryMode === "hand"){
                    vm.handShow = true;
                    vm.copyShow = false;
                }else if(vm.entryMode === "copy"){
                    vm.handShow = false;
                    vm.copyShow = true;
                }
            },
            // 复制--选择考核方案
            checkScheme(schemeId,index){
                let vm = this;
                for(let i = 0; i < vm.courseAssessmentList.length; i++ ){
                    if(index == i){
                        continue;
                    }
                    vm.courseAssessmentList[i].check = false;
                }
                // console.log(schemeId);
            },
            // 表格合计列
            getSummaries(params){
                let vm = this;
                const { columns, data } = params;
                const sums = [];
                columns.forEach((column, index) => {
                    if (index === 0) {
                        sums[index] = '合计';
                        return;
                    }else if(index == 1){
                        const values = vm.form.detailList.map(item => Number(item.scorePercent));
                        if (!values.every(value => isNaN(value))) {
                            sums[index] = values.reduce((prev, curr) => {
                                const value = Number(curr);
                                if (!isNaN(value)) {
                                    return prev + curr;
                                } else {
                                    return prev;
                                }
                            }, 0);
                            // sums[index] += ' 元';
                        }
                    }else {
                        sums[index] = '';
                    }
                })
                return sums;
            },

        },
    };
</script>
<style scoped>

</style>